import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import 'package:get/get.dart';

import '../../../../generated/assets.dart';
import '../../../services/utils.dart';
import '../../res/color_res.dart';
import '../../widgets/text_field_widgets.dart';
import '../controllers/login_controller.dart';

class LoginView extends GetView<LoginController> {
  const LoginView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          hideKeyboard();
        },
        child: SafeArea(
          child: Stack(
            children: [
              _mainBody(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _topBackgroundImg() {
    return SizedBox(
      width: 375.w,
      height: 250.w,
      child: Stack(
        children: [
          // 背景图片
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Image.asset(
              Assets.imagesBackgroud,
              height: 223.w,
            ),
          ),
          // Logo和欢迎文字
        ],
      ),
    );
  }

  Widget _mainBody() {
    return Positioned.fill(
      child: SingleChildScrollView(
        physics: const ClampingScrollPhysics(),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _topBackgroundImg(),
            segmentWidget(),
            _account(),
            passwordWidget(),
            Obx(() => controller.currentTabIndex.value == 0
                    ? Container() // 登录时不显示邮箱字段
                    : emailWidget() // 注册时显示邮箱字段
                ),
            _verification(),
            _loginBtn(),
            _protocol(),
            SizedBox(height: 30.w), // 底部间距
          ],
        ),
      ),
    );
  }

  Widget segmentWidget() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 30.w, vertical: 0.w),
      height: 45.w,
      decoration: BoxDecoration(
        color: const Color(0xFFF5F5F5),
        borderRadius: BorderRadius.circular(25.w),
      ),
      child: TabBar(
        controller: controller.tabController,
        indicator: BoxDecoration(
          gradient: const LinearGradient(
            colors: [
              Color(0xFF5A85D4),
              Color(0xFF3561B9),
              Color(0xFF284A8F),
            ],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          ),
          borderRadius: BorderRadius.circular(25.w),
        ),
        indicatorSize: TabBarIndicatorSize.tab,
        dividerHeight: 0,
        labelColor: Colors.white,
        unselectedLabelColor: const Color(0xFF666666),
        labelStyle: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.w500,
        ),
        unselectedLabelStyle: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.normal,
        ),
        tabs: const [
          Tab(
            text: '登录',
          ),
          Tab(
            text: '注册',
          ),
        ],
      ),
    );
  }

  Widget _account() {
    final adjustPadding = 11.w;
    return Padding(
      padding: EdgeInsets.only(
        top: 20.w,
        left: 25.w,
        right: 34.w,
      ),
      child: AccountTextField(
        adjustPadding: adjustPadding,
        controller: controller.accountController,
        keyboardType: TextInputType.phone,
        prefix: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.only(top: 10.w, right: 10.w),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    Assets.imagesIcLoginPhone,
                    width: 24.w,
                    height: 24.w,
                  ),
                  Text(
                    '用户名',
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.normal,
                      color: const Color(loginPagePrefixTextColor),
                    ),
                  ),
                  SizedBox(width: 4.w),
                ],
              ),
            ),
          ],
        ),
        hintText: '请输入用户名',
        hintStyle: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.normal,
          // color: const Color(colorGray9),
          color: const Color(0xffA4A4A4),
        ),
        onChanged: (text) {
          myLog("输入账号：$text");
        },
        onEditingComplete: () {
          myLog("账号输入结束");
          FocusManager.instance.primaryFocus?.unfocus();
        },
        onSubmitted: (text) {
          myLog("提交账号：$text");
        },
      ),
    );
  }

  Widget _verification() {
    var adjustPadding = 11.w;

    return Padding(
      padding: EdgeInsets.only(
        top: 26.w,
        left: 25.w,
        right: 34.w,
      ),
      child: Row(
        children: [
          Expanded(
            child: AccountTextField(
              adjustPadding: adjustPadding,
              controller: controller.captchaController,
              prefix: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.only(top: 10.w, right: 10.w),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Image.asset(
                          Assets.imagesIcLoginYanzhengma,
                          width: 24.w,
                          height: 24.w,
                        ),
                        Text(
                          '验证码',
                          style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: FontWeight.normal,
                            color: const Color(loginPagePrefixTextColor),
                          ),
                        ),
                        SizedBox(width: 4.w),
                      ],
                    ),
                  ),
                ],
              ),
              hintText: '请输入图片验证码',
              hintStyle: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.normal,
                // color: const Color(colorGray9),
                color: const Color(0xffA4A4A4),
              ),
              onEditingComplete: () {
                myLog("验证码输入结束");
                hideKeyboard();
              },
              onSubmitted: (text) {
                myLog("提交验证码：$text");
              },
              autofillHints: const [AutofillHints.oneTimeCode],
            ),
          ),
          SizedBox(width: 12.w),
          _buildCaptchaButton(),
        ],
      ),
    );
  }

  Widget emailWidget() {
    final adjustPadding = 11.w;
    return Padding(
      padding: EdgeInsets.only(
        top: 20.w,
        left: 25.w,
        right: 34.w,
      ),
      child: AccountTextField(
        adjustPadding: adjustPadding,
        controller: controller.emailController,
        keyboardType: TextInputType.emailAddress,
        prefix: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.only(top: 10.w, right: 10.w),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    Assets.imagesIcLoginPhone,
                    width: 24.w,
                    height: 24.w,
                  ),
                  Text(
                    '邮箱',
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.normal,
                      color: const Color(loginPagePrefixTextColor),
                    ),
                  ),
                  SizedBox(width: 4.w),
                ],
              ),
            ),
          ],
        ),
        hintText: '请输入邮箱',
        hintStyle: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.normal,
          // color: const Color(colorGray9),
          color: const Color(0xffA4A4A4),
        ),
        onChanged: (text) {
          myLog("输入邮箱：$text");
        },
        onEditingComplete: () {
          myLog("邮箱输入结束");
          FocusManager.instance.primaryFocus?.unfocus();
        },
        onSubmitted: (text) {
          myLog("提交邮箱：$text");
        },
      ),
    );
  }

  Widget passwordWidget() {
    final adjustPadding = 11.w;
    return Padding(
      padding: EdgeInsets.only(
        top: 20.w,
        left: 25.w,
        right: 34.w,
      ),
      child: AccountTextField(
        adjustPadding: adjustPadding,
        controller: controller.passwordController,
        keyboardType: TextInputType.visiblePassword,
        prefix: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.only(top: 10.w, right: 10.w),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    Assets.imagesIcLoginPhone,
                    width: 24.w,
                    height: 24.w,
                  ),
                  Text(
                    '密码',
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.normal,
                      color: const Color(loginPagePrefixTextColor),
                    ),
                  ),
                  SizedBox(width: 4.w),
                ],
              ),
            ),
          ],
        ),
        hintText: '请输入密码',
        hintStyle: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.normal,
          // color: const Color(colorGray9),
          color: const Color(0xffA4A4A4),
        ),
        onChanged: (text) {
          myLog("输入密码：$text");
        },
        onEditingComplete: () {
          myLog("密码输入结束");
          FocusManager.instance.primaryFocus?.unfocus();
        },
        onSubmitted: (text) {
          myLog("提交密码：$text");
        },
      ),
    );
  }

  // 构建图片验证码按钮
  Widget _buildCaptchaButton() {
    return GestureDetector(
      onTap: () {
        controller.getCaptchaImage();
      },
      child: Container(
        width: 100.w,
        height: 42.w,
        decoration: BoxDecoration(
          border: Border.all(
            color: const Color(0xFFDEDEDE),
            width: 1,
          ),
          borderRadius: BorderRadius.circular(4.w),
          color: Colors.white,
        ),
        child: Obx(() {
          if (controller.isLoadingCaptcha.value) {
            // 加载中显示加载指示器
            return Center(
              child: SizedBox(
                width: 20.w,
                height: 20.w,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    const Color(0xFF3561B9),
                  ),
                ),
              ),
            );
          } else if (controller.captchaImageUrl.value.isEmpty) {
            // 初始状态显示提示文字
            return Center(
              child: Text(
                '点击获取\n验证码',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 12.sp,
                  color: const Color(0xFF666666),
                  height: 1.2,
                ),
              ),
            );
          } else {
            // 显示验证码图片 (base64格式)
            return ClipRRect(
              borderRadius: BorderRadius.circular(4.w),
              child: _buildCaptchaImage(),
            );
          }
        }),
      ),
    );
  }

  // 构建验证码图片 (处理base64格式)
  Widget _buildCaptchaImage() {
    try {
      final imageData = controller.captchaImageUrl.value;
      if (imageData.isEmpty) {
        return _buildErrorWidget();
      }

      // 处理base64数据，移除data:image/png;base64,前缀（如果存在）
      String base64String = imageData;
      if (base64String.startsWith('data:image')) {
        base64String = base64String.substring(base64String.indexOf(',') + 1);
      }

      // 解码base64数据
      final bytes = base64Decode(base64String);

      return Image.memory(
        bytes,
        fit: BoxFit.cover,
        width: 100.w,
        height: 42.w,
        errorBuilder: (context, error, stackTrace) {
          return _buildErrorWidget();
        },
      );
    } catch (e) {
      myLog('解析验证码图片失败: $e');
      return _buildErrorWidget();
    }
  }

  // 构建错误显示组件
  Widget _buildErrorWidget() {
    return Center(
      child: Text(
        '加载失败\n点击重试',
        textAlign: TextAlign.center,
        style: TextStyle(
          fontSize: 10.sp,
          color: Colors.red,
          height: 1.2,
        ),
      ),
    );
  }

  Widget _loginBtn() {
    return Padding(
      padding: EdgeInsets.only(top: 70.w, left: 25.w, right: 25.w),
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.transparent,
          elevation: 0,
          minimumSize: Size(0, 46.w),
          padding: EdgeInsets.zero,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(4.w),
          ),
        ),
        onPressed: () async {
          if (!controller.isAgree.value) {
            SmartDialog.showToast(
              '请同意《博客APP隐私政策》',
              alignment: Alignment.center,
            );
            return;
          }
          controller.currentTabIndex.value == 0 ?
          controller.login(
            username: controller.accountController.text,
            password: controller.passwordController.text,
            code: controller.captchaController.text, // 使用图片验证码
          ):controller.register(
            username: controller.accountController.text,
            password: controller.passwordController.text,
            code: controller.captchaController.text,
            email: controller.emailController.text,
          );
        },
        child: Container(
          width: double.infinity,
          height: 46.w,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            gradient: const LinearGradient(
              colors: [
                Color(0xFF5A85D4),
                Color(0xFF3561B9),
                Color(0xFF284A8F),
              ],
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
            ),
            borderRadius: BorderRadius.circular(4.w),
          ),
          child: Obx(() => Text(
                controller.currentTabIndex.value == 0 ? "登录" : "注册",
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.normal,
                ),
              )),
        ),
      ),
    );
  }

  Widget _protocol() {
    return Padding(
      padding: EdgeInsets.only(top: 20.w),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          GestureDetector(
            onTap: () => controller.isAgree.value = !controller.isAgree.value,
            child: Obx(
              () => Image(
                image: AssetImage(controller.isAgree.value
                    ? Assets.imagesLoginCheckedProtocol
                    : Assets.imagesLoginUncheckProtocol),
                width: 13.w,
                height: 13.w,
              ),
            ),
          ),
          SizedBox(width: 8.w),
          Text.rich(
            TextSpan(
              children: [
                TextSpan(
                  text: '我已经阅读并同意',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(loginPageProtocolColor),
                  ),
                ),
                TextSpan(
                  text: '《博客APP隐私政策》',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(loginPageProtocolLinkColor),
                    decoration: TextDecoration.none,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      myLog('点击了《博客APP隐私政策》');
                    },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
